package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.db.Question;
import com.tanhua.model.domain.db.Settings;
import com.tanhua.model.domain.db.User;
import com.tanhua.model.domain.db.UserInfo;
import com.tanhua.model.vo.HuanXinUserVo;
import com.tanhua.model.vo.SettingsVo;
import com.tanhua.model.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

@Service
public class UsersService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private SettingsApi settingsApi;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private QuestionApi questionApi;

    /**
     * 1、获取当前登陆者个人信息资料
     * @return
     */
    public UserInfoVo findUserInfoById(Long id) {

        UserInfo ui=userInfoApi.findUserInfoById(id);

        UserInfoVo uif=new UserInfoVo();//null
        //将数据库查询的数据封装到页面响应对象中
        BeanUtil.copyProperties(ui,uif);
        //uif.setAge(ui.getAge().toString());
        uif.setAge(StrUtil.toString(ui.getAge()));
        return uif;
    }

    /**
     *
     * @param userInfo
     */
    public void updateUserInfo(UserInfo userInfo) {
        Long id = UserHolder.getUserId();
        //补全用户id
        userInfo.setId(id);
        userInfoApi.saveOrUpdate(userInfo);
    }

    /**
     * 查找用户通用设置
     * @param id
     * @return
     */
    public SettingsVo findSetting(Long id) {
        SettingsVo settingsVo = new SettingsVo();
        settingsVo.setId(id);
        User user = userApi.findByID(id);
        settingsVo.setPhone(user.getMobile());
        Question question = questionApi.findQuestionByUserId(id);
        if (BeanUtil.isEmpty(question)){
            settingsVo.setStrangerQuestion("你喜欢玩游戏么");
        }else{
            settingsVo.setStrangerQuestion(question.getTxt());
        }

        Settings setting = settingsApi.findSetting(id);
        if(setting != null) {
            settingsVo.setGonggaoNotification(setting.getGonggaoNotification());
            settingsVo.setPinglunNotification(setting.getPinglunNotification());
            settingsVo.setLikeNotification(setting.getLikeNotification());
        }
        return settingsVo;
    }

    //根据id寻找环信用户
    public HuanXinUserVo findHuanXinUser(Long userId) {
        User byID = userApi.findByID(userId);
        HuanXinUserVo userVo = new HuanXinUserVo();
        userVo.setUsername(byID.getHxUser());
        userVo.setPassword(byID.getHxPassword());
        return userVo;
    }
}
